package controller

import (
	"delivery-server/service"
	"delivery-server/utils/response"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
	"github.com/kataras/iris/v12/sessions"
	"strconv"
)

type CategoryController struct {

	// 上下文对象
	Ctx iris.Context

	// 菜式功能实体
	Service service.CategoryService

	// session对象
	Session *sessions.Session
}

// PostAdd
// 接口：/category/add
// name：新菜式的名称
func (cc *CategoryController) PostAdd() mvc.Result {

	name := cc.Ctx.FormValue("name")

	if name == "" {
		return response.ParamLack()
	}

	code := cc.Service.TryToAddCategory(name)
	return response.Template(code, code == response.SuccessCode)
}

// GetAll 获取所有菜式
// 接口：/category/all
func (cc *CategoryController) GetAll() mvc.Result {
	results, err := cc.Service.QueryAllCategories()
	if err != nil {
		return response.ServerErr()
	}
	return response.Success(results)
}

// PostDelete 删除菜式
// 接口：/category/delete
// categoryId：菜式id
func (cc *CategoryController) PostDelete() mvc.Result {

	categoryIdStr := cc.Ctx.FormValue("categoryId")

	if categoryIdStr == "" {
		return response.ParamLack()
	}

	categoryId, err := strconv.Atoi(categoryIdStr)
	if err != nil {
		return response.ParamErr()
	}

	err = cc.Service.DeleteCategory(categoryId)
	if err != nil {
		return response.ServerErr()
	}

	return response.Success(true)
}
